package twitter;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class CustomXpath {
	Document doc;
	XPath xPath;
	
	public CustomXpath(String string) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = domFactory.newDocumentBuilder();
		InputSource inputSource = new InputSource( new StringReader( string ) );
		
		doc = builder.parse(inputSource);
		
		XPathFactory xPathFactory =  XPathFactory.newInstance();
		xPath = xPathFactory.newXPath();
	}

	/**
	 * Compile the xpath-expression
	 * @param xpath
	 * @return
	 */
	public NodeList execute(String xpath) {
		try {
			XPathExpression expression = xPath.compile(xpath);
			NodeList results = (NodeList) expression.evaluate(doc,XPathConstants.NODESET);
			return results;
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * If xpath-expression returns more than one result, this function will return only the first one
	 * @param xpath The xpath-expression
	 * @return
	 */
	public String getFirstTextContent(String xpath) {
		NodeList results = execute(xpath);
		if(results.getLength() > 0) {
			Node node = results.item(0);
			return node.getTextContent();
		}
		else {
			return null;
		}
	}
	
	/**
	 * Make a xpath-query on a xml-string
	 * @param string The xml string
	 * @param xpath The xpath-expression
	 * @return NodeList Results
	 */
	public static NodeList parseXMLWithXPath(String string, String xpath) {		
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			InputSource inputSource = new InputSource( new StringReader( string ) );
			
			Document doc = builder.parse(inputSource);
			
			XPathFactory xPathFactory =  XPathFactory.newInstance();
			XPath xPath = xPathFactory.newXPath();
			
			XPathExpression expression = xPath.compile(xpath);
			NodeList results = (NodeList) expression.evaluate(doc,XPathConstants.NODESET);
			
			return results;
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
